package com.dl698.axdr;

import com.dl698.asn1.axdr.AxdrType;
import com.dl698.asn1.axdr.AxdrInteger;
import com.dl698.asn1.axdr.AxdrEnum;
import com.dl698.util.ReverseByteArrayInputStream;
import com.dl698.util.ReverseByteArrayOutputStream;

/**
 * ScalerUnit类
 * 实现标量单位的编解码
 * 
 * @author wind
 * @version 1.1.1
 */
public class ScalerUnit implements AxdrType {

    private byte[] dataCode = null;
    private AxdrInteger t1 = null;
    private AxdrEnum unit = null;

    /**
     * 默认构造函数
     */
    public ScalerUnit() {
    }

    /**
     * 设置数据编码
     * 
     * @param dataCode 数据编码
     */
    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    /**
     * 设置标量单位参数
     * 
     * @param t1   标量
     * @param unit 单位
     */
    public void setAll(AxdrInteger t1, AxdrEnum unit) {
        this.t1 = t1;
        this.unit = unit;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) {
        // TODO: 实现解码逻辑
        return 0;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) {
        int codeLength;

        if (dataCode != null) {
            codeLength = dataCode.length;
            for (int i = dataCode.length - 1; i >= 0; i--) {
                try {
                    output.write(dataCode[i]);
                } catch (java.io.IOException e) {
                    throw new RuntimeException("IO exception during encode", e);
                }
            }
        } else {
            if (unit != null && t1 != null) {
                codeLength = 0;
                codeLength += unit.encode(output);
                codeLength += t1.encode(output);
            } else {
                throw new RuntimeException("unit or t1 is null");
            }
        }
        return codeLength;
    }

    /**
     * 编码并保存
     * 
     * @param encodingSizeGuess 编码大小预估
     */
    public void encodeAndSave(int encodingSizeGuess) {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    @Override
    public String toString() {
        if (unit != null && t1 != null) {
            return "sequence: {" + "t1: " + t1 + ", unit: " + unit + "}";
        } else {
            return "unit or t1 is null";
        }
    }
}